#import <UIKit/UIKit.h>
#import <GameKit/GameKit.h>
#import "social.h"
#import "gamecenter.h"
#import "UnityAppController.h"
#import "UnityAppController+Rendering.h"

@implementation GamecenterPlatformProvider
{
    SocialRequestCompletionHandler authHandler;
    NSError *userErr;
    SocialUserInfoResponse *userResponse;
}
-(id)init
{
    return [super init];
}
-(void)launch:(NSDictionary *)launchOptions{
    
}
-(void)setAppKey:(NSString *)appKey
   withAppSecret:(NSString *)appSecret
 withRedirectURL:(NSString *)redirectURL{
    
}
-(void)_init
{
    if (userResponse != nil){
        authHandler(userResponse, userErr);
        return;
    }
    SocialUserInfoResponse *response = [[SocialUserInfoResponse alloc] init];
    GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
    localPlayer.authenticateHandler = ^(UIViewController * __nullable viewController, NSError * __nullable error){
        NSLog(@"已经授权1，playerID : %@", [GKLocalPlayer localPlayer].playerID);
        response.openId = localPlayer.playerID;
        response.nickName = localPlayer.alias;
        NSError *err;
        if ([[GKLocalPlayer localPlayer] isAuthenticated]) {
            response.openId = localPlayer.playerID;
            
            [[GKLocalPlayer localPlayer] generateIdentityVerificationSignatureWithCompletionHandler:^(NSURL *publicKeyUrl, NSData *signature, NSData *salt, uint64_t timestamp, NSError *error) {
                if (!error) {
                    response.accessToken = @"";
                }
                userResponse = response;
                userErr = nil;
                authHandler(response, err);
            }];
        }else if(viewController){
            UnityAppController* controller = GetAppController();
            [[controller rootViewController] presentViewController: viewController animated:NO completion:nil];
        }else{
            if (!error){
                // 授权完成
            }else{
                // 取消授权
                NSLog(@"AuthPlayer error: %@", [error localizedDescription]);
                err = [NSError errorWithDomain:@"gamecenter auth" code:10 userInfo:nil];
            }
            userResponse = response;
            userErr = err;
            authHandler(response, err);
        }
    };
}
-(void)AuthorizeWithUserInfo:(NSDictionary *)userInfo
       withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
    if (localPlayer.isAuthenticated){
        completionHandler(userResponse, userErr);
        return;
    }
    [self _init];
}
-(void)AuthorizedWithUserInfo:(NSDictionary *)userInfo
       withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    authHandler = completionHandler;
    [self _init];
}

-(void)ShareWithObject:(SocialMessageObject *)object
 withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    NSError *err = [NSError errorWithDomain:@"gamecenter share" code:10 userInfo:nil];
    completionHandler(nil,err);
}
-(void)LeaderboardWith:(NSString *)key withValue:(int) value
 withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
    if (![localPlayer isAuthenticated]){
        NSError *err = [NSError errorWithDomain:@"gamecenter leaderboard no auth" code:10 userInfo:nil];
        completionHandler(nil,err);
        return;
    }
    GKScore *scoreReporter = [[GKScore alloc] initWithLeaderboardIdentifier: key];
    scoreReporter.value = value;
    scoreReporter.context = 0;
    
    [GKScore reportScores:@[scoreReporter] withCompletionHandler:^(NSError *error) {
        if (error == nil) {
            completionHandler(nil,nil);
        } else {
            NSLog(@"Unable to report score!");
            completionHandler(nil,error);
        }
    }];
}
-(void)AchievementWith:(NSString *)key withValue:(int) value
 withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
    if (![localPlayer isAuthenticated]){
        NSError *err = [NSError errorWithDomain:@"gamecenter achievement no auth" code:10 userInfo:nil];
        completionHandler(nil,err);
        return;
    }
    GKAchievement *achievement = [[GKAchievement alloc] initWithIdentifier:key];
    if (achievement && achievement.percentComplete != 100.0) {
        if (value == 0){
            achievement.percentComplete = 100.0;
        }else{
            achievement.percentComplete = value;
        }
        achievement.showsCompletionBanner = FALSE;
        [GKAchievement reportAchievements:@[achievement] withCompletionHandler:^(NSError *error) {
            if (error == nil) {
                completionHandler(nil,nil);
            } else {
                NSLog(@"Unable to report score!");
                completionHandler(nil,error);
            }
        }];
    }else{
        completionHandler(nil,nil);
    }
}
-(BOOL)handleOpenURL:(NSURL *)url{
    return false;
}
-(BOOL)handleOpenURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return false;
}
-(BOOL)handleOpenURL:(NSURL *)url options:(NSDictionary*)options{
    return false;
}

-(BOOL)isInstall{
    return true;
}
-(BOOL)isSupport{
    return false;
}

-(BOOL)isLeaderboard{
    return true;
}
-(BOOL)isAchievement{
    return true;
}
@end
